Data Scientist Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App

This notebook walks you through one of the most popular Udacity projects across machine learning and artificial intellegence nanodegree programs. The goal is to classify images of dogs according to their breed.

If you are looking for a more guided capstone project related to deep learning and convolutional neural networks, this might be just it. Notice that even if you follow the notebook to creating your classifier, you must still create a blog post or deploy an application to fulfill the requirements of the capstone project.

Also notice, you may be able to use only parts of this notebook (for example certain coding portions or the data) without completing all parts and still meet all requirements of the capstone project.


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('../../../data/dog_images/train')
valid_files, valid_targets = load_dataset('../../../data/dog_images/valid')
test_files, test_targets = load_dataset('../../../data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("../../../data/dog_images/train/*/"))]

#Save classes list to csv 
d = {'breed': dog_names}
df_dog_names= pd.DataFrame(d)
df_dog_names.to_csv('dog_names.csv')

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("../../../data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
count_human=0
for img in human_files_short:
    if face_detector(img)==True:
        count_human+=1
    else:
        pass
count_dog=0
for img in dog_files_short:
    if face_detector(img)==True:
        count_dog+=1
    else:
        pass

print('{}% of human images are detected with human face.'.format(count_human))
print('{}% of dog images are detected with human face.'.format(100-count_dog))
100% of human images are detected with human face.
89% of dog images are detected with human face.

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [6]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [7]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [8]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [9]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [11]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [12]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
count_human=0
for img in human_files_short:
    if dog_detector(img)==True:
        count_human+=1
    else:
        pass
count_dog=0
for img in dog_files_short:
    if dog_detector(img)==True:
        count_dog+=1
    else:
        pass
print('{}% of human images are detected with dog face.'.format(100-count_human))
print('{}% of dog images are detected with dog face.'.format(count_dog))
100% of human images are detected with dog face.
100% of dog images are detected with dog face.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [13]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:10<00:00, 94.51it/s] 
100%|██████████| 835/835 [00:07<00:00, 104.89it/s]
100%|██████████| 836/836 [00:07<00:00, 106.33it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

Construct a convnet that consist of following:

  • Conv layer with 16 filters of size 3x3, and using 'relu' activation function, followed by Max Pooling layer of pool size 2x2.
  • Conv layer with 32 filters of size 3x3, and using 'relu' activation function, followed by Max Pooling layer of pool size 2x2.
  • Conv layer with 32 filters of size 3x3, and using 'relu' activation function, followed by Max Pooling layer of pool size 2x2.
  • Flatten the 2D array into 1D
  • Fully connected layer with 512 neurons, using 'relu' activation function
  • Fully connected layer with 133 neurons with a softmax function.

Did not apply Dropout after convolutional layer due to spatial relationships encoded in feature maps

  • Applies it only for fully connected layer

Use Batch Normalization after each convolutional layer

  • Helps with vanishing/exploding gradients during training
  • Helps in regularization
In [89]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.layers import BatchNormalization

model = Sequential()
model.add(Conv2D(16, (3,3), activation='relu', input_shape=(224, 224, 3)))
model.add(BatchNormalization())
model.add(MaxPooling2D(2, 2))
model.add(Conv2D(32, (3,3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(2,2))
model.add(Conv2D(32, (3,3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(2,2))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(133, activation='softmax'))

### TODO: Define your architecture.

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_11 (Conv2D)           (None, 222, 222, 16)      448       
_________________________________________________________________
batch_normalization_2 (Batch (None, 222, 222, 16)      64        
_________________________________________________________________
max_pooling2d_11 (MaxPooling (None, 111, 111, 16)      0         
_________________________________________________________________
conv2d_12 (Conv2D)           (None, 109, 109, 32)      4640      
_________________________________________________________________
batch_normalization_3 (Batch (None, 109, 109, 32)      128       
_________________________________________________________________
max_pooling2d_12 (MaxPooling (None, 54, 54, 32)        0         
_________________________________________________________________
conv2d_13 (Conv2D)           (None, 52, 52, 32)        9248      
_________________________________________________________________
batch_normalization_4 (Batch (None, 52, 52, 32)        128       
_________________________________________________________________
max_pooling2d_13 (MaxPooling (None, 26, 26, 32)        0         
_________________________________________________________________
flatten_5 (Flatten)          (None, 21632)             0         
_________________________________________________________________
dense_30 (Dense)             (None, 512)               11076096  
_________________________________________________________________
dense_31 (Dense)             (None, 133)               68229     
=================================================================
Total params: 11,158,981
Trainable params: 11,158,821
Non-trainable params: 160
_________________________________________________________________

Compile the Model

In [90]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [91]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 10

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.8299 - acc: 0.0128Epoch 00001: val_loss improved from inf to 15.80966, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 38s 6ms/step - loss: 15.8307 - acc: 0.0127 - val_loss: 15.8097 - val_acc: 0.0180
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.8532 - acc: 0.0161Epoch 00002: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.8516 - acc: 0.0162 - val_loss: 15.9222 - val_acc: 0.0120
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.8204 - acc: 0.0180Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.8189 - acc: 0.0181 - val_loss: 15.9664 - val_acc: 0.0084
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.7825 - acc: 0.0204Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.7835 - acc: 0.0204 - val_loss: 15.8572 - val_acc: 0.0156
Epoch 5/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.7391 - acc: 0.0228Epoch 00005: val_loss improved from 15.80966 to 15.77257, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s 5ms/step - loss: 15.7403 - acc: 0.0228 - val_loss: 15.7726 - val_acc: 0.0204
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.7054 - acc: 0.0251Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.7066 - acc: 0.0250 - val_loss: 15.8842 - val_acc: 0.0132
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.7278 - acc: 0.0237Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.7290 - acc: 0.0237 - val_loss: 15.8845 - val_acc: 0.0132
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.7131 - acc: 0.0245Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.7143 - acc: 0.0244 - val_loss: 15.9038 - val_acc: 0.0108
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.6566 - acc: 0.0279Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.6579 - acc: 0.0278 - val_loss: 15.8735 - val_acc: 0.0144
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 15.6831 - acc: 0.0264Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 36s 5ms/step - loss: 15.6844 - acc: 0.0263 - val_loss: 15.7899 - val_acc: 0.0204
Out[91]:
<keras.callbacks.History at 0x7f9960242b00>

Load the Model with the Best Validation Loss

In [23]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [24]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 8.2536%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [25]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
In [50]:
train_VGG16.shape
Out[50]:
(6680, 7, 7, 512)

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [26]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [27]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [28]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6580/6680 [============================>.] - ETA: 0s - loss: 12.6714 - acc: 0.1052Epoch 00001: val_loss improved from inf to 11.21579, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 300us/step - loss: 12.6437 - acc: 0.1070 - val_loss: 11.2158 - val_acc: 0.1832
Epoch 2/20
6560/6680 [============================>.] - ETA: 0s - loss: 10.6226 - acc: 0.2596Epoch 00002: val_loss improved from 11.21579 to 10.67597, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 10.6241 - acc: 0.2599 - val_loss: 10.6760 - val_acc: 0.2539
Epoch 3/20
6580/6680 [============================>.] - ETA: 0s - loss: 10.2488 - acc: 0.3146Epoch 00003: val_loss improved from 10.67597 to 10.34173, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 10.2240 - acc: 0.3162 - val_loss: 10.3417 - val_acc: 0.2946
Epoch 4/20
6540/6680 [============================>.] - ETA: 0s - loss: 10.0295 - acc: 0.3404Epoch 00004: val_loss improved from 10.34173 to 10.28385, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 252us/step - loss: 10.0143 - acc: 0.3415 - val_loss: 10.2839 - val_acc: 0.3018
Epoch 5/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.8826 - acc: 0.3550Epoch 00005: val_loss improved from 10.28385 to 10.20875, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 248us/step - loss: 9.8728 - acc: 0.3555 - val_loss: 10.2088 - val_acc: 0.3078
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.8106 - acc: 0.3713Epoch 00006: val_loss improved from 10.20875 to 10.15713, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 9.8054 - acc: 0.3717 - val_loss: 10.1571 - val_acc: 0.3269
Epoch 7/20
6580/6680 [============================>.] - ETA: 0s - loss: 9.7344 - acc: 0.3772Epoch 00007: val_loss improved from 10.15713 to 9.97609, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 9.7168 - acc: 0.3783 - val_loss: 9.9761 - val_acc: 0.3341
Epoch 8/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.5792 - acc: 0.3921Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 248us/step - loss: 9.5778 - acc: 0.3922 - val_loss: 10.0780 - val_acc: 0.3234
Epoch 9/20
6580/6680 [============================>.] - ETA: 0s - loss: 9.5281 - acc: 0.3956Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 250us/step - loss: 9.5378 - acc: 0.3951 - val_loss: 10.0091 - val_acc: 0.3365
Epoch 10/20
6540/6680 [============================>.] - ETA: 0s - loss: 9.4615 - acc: 0.4011Epoch 00010: val_loss improved from 9.97609 to 9.87115, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 9.4858 - acc: 0.3996 - val_loss: 9.8712 - val_acc: 0.3329
Epoch 11/20
6460/6680 [============================>.] - ETA: 0s - loss: 9.3512 - acc: 0.4077Epoch 00011: val_loss improved from 9.87115 to 9.80338, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 248us/step - loss: 9.3497 - acc: 0.4078 - val_loss: 9.8034 - val_acc: 0.3437
Epoch 12/20
6560/6680 [============================>.] - ETA: 0s - loss: 9.1752 - acc: 0.4168Epoch 00012: val_loss improved from 9.80338 to 9.61938, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 9.1467 - acc: 0.4183 - val_loss: 9.6194 - val_acc: 0.3425
Epoch 13/20
6520/6680 [============================>.] - ETA: 0s - loss: 8.9745 - acc: 0.4262Epoch 00013: val_loss improved from 9.61938 to 9.39421, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 247us/step - loss: 8.9708 - acc: 0.4265 - val_loss: 9.3942 - val_acc: 0.3545
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.8091 - acc: 0.4393Epoch 00014: val_loss improved from 9.39421 to 9.32813, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 249us/step - loss: 8.8044 - acc: 0.4397 - val_loss: 9.3281 - val_acc: 0.3629
Epoch 15/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.6929 - acc: 0.4441Epoch 00015: val_loss improved from 9.32813 to 9.20341, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 8.6785 - acc: 0.4451 - val_loss: 9.2034 - val_acc: 0.3605
Epoch 16/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.5703 - acc: 0.4535Epoch 00016: val_loss improved from 9.20341 to 9.14098, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 8.5720 - acc: 0.4534 - val_loss: 9.1410 - val_acc: 0.3796
Epoch 17/20
6520/6680 [============================>.] - ETA: 0s - loss: 8.4936 - acc: 0.4578Epoch 00017: val_loss improved from 9.14098 to 9.00494, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 8.4944 - acc: 0.4573 - val_loss: 9.0049 - val_acc: 0.3784
Epoch 18/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.3613 - acc: 0.4667Epoch 00018: val_loss improved from 9.00494 to 8.89527, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 8.3549 - acc: 0.4672 - val_loss: 8.8953 - val_acc: 0.3856
Epoch 19/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.2821 - acc: 0.4726Epoch 00019: val_loss improved from 8.89527 to 8.87820, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 8.2704 - acc: 0.4732 - val_loss: 8.8782 - val_acc: 0.3820
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.1549 - acc: 0.4825Epoch 00020: val_loss improved from 8.87820 to 8.77901, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 8.1523 - acc: 0.4825 - val_loss: 8.7790 - val_acc: 0.3892
Out[28]:
<keras.callbacks.History at 0x7f996bbc0e10>

Load the Model with the Best Validation Loss

In [29]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [30]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 38.6364%

Predict Dog Breed with the Model

In [31]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [85]:
#Preliminary Test on  VGG19
### Obtain bottleneck features from Inception.
bottleneck_features = np.load('bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features['train']
valid_VGG19 = bottleneck_features['valid']
test_VGG19 = bottleneck_features['test']
### Define your architecture.
VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(133, activation='softmax'))
VGG19_model.summary()
### Compile the model.
VGG19_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
### Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)
VGG19_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
### Load the model weights with the best validation loss.
VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')
### Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]
# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_14  (None, 512)               0         
_________________________________________________________________
dense_27 (Dense)             (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6620/6680 [============================>.] - ETA: 0s - loss: 11.7914 - acc: 0.1394Epoch 00001: val_loss improved from inf to 9.95686, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 322us/step - loss: 11.7613 - acc: 0.1409 - val_loss: 9.9569 - val_acc: 0.2419
Epoch 2/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.9733 - acc: 0.3367Epoch 00002: val_loss improved from 9.95686 to 8.91379, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 253us/step - loss: 8.9622 - acc: 0.3380 - val_loss: 8.9138 - val_acc: 0.3401
Epoch 3/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.3337 - acc: 0.4184Epoch 00003: val_loss improved from 8.91379 to 8.61520, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 8.3491 - acc: 0.4169 - val_loss: 8.6152 - val_acc: 0.3677
Epoch 4/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.0987 - acc: 0.4511Epoch 00004: val_loss improved from 8.61520 to 8.52012, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 8.1035 - acc: 0.4503 - val_loss: 8.5201 - val_acc: 0.3904
Epoch 5/20
6520/6680 [============================>.] - ETA: 0s - loss: 7.9830 - acc: 0.4776Epoch 00005: val_loss improved from 8.52012 to 8.45726, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 7.9926 - acc: 0.4769 - val_loss: 8.4573 - val_acc: 0.4048
Epoch 6/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.9591 - acc: 0.4859Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 7.9390 - acc: 0.4874 - val_loss: 8.5008 - val_acc: 0.4024
Epoch 7/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.8979 - acc: 0.4940Epoch 00007: val_loss improved from 8.45726 to 8.39030, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 7.9009 - acc: 0.4939 - val_loss: 8.3903 - val_acc: 0.4132
Epoch 8/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.7970 - acc: 0.5042Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 7.7866 - acc: 0.5043 - val_loss: 8.4342 - val_acc: 0.4072
Epoch 9/20
6540/6680 [============================>.] - ETA: 0s - loss: 7.7537 - acc: 0.5064Epoch 00009: val_loss improved from 8.39030 to 8.31232, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 252us/step - loss: 7.7405 - acc: 0.5072 - val_loss: 8.3123 - val_acc: 0.4156
Epoch 10/20
6520/6680 [============================>.] - ETA: 0s - loss: 7.6141 - acc: 0.5107Epoch 00010: val_loss improved from 8.31232 to 8.07173, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 253us/step - loss: 7.6109 - acc: 0.5103 - val_loss: 8.0717 - val_acc: 0.4192
Epoch 11/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.5018 - acc: 0.5231Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 7.4726 - acc: 0.5250 - val_loss: 8.1482 - val_acc: 0.4240
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.4256 - acc: 0.5284Epoch 00012: val_loss improved from 8.07173 to 8.06394, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 7.4227 - acc: 0.5286 - val_loss: 8.0639 - val_acc: 0.4251
Epoch 13/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.3487 - acc: 0.5350Epoch 00013: val_loss improved from 8.06394 to 8.00593, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 7.3435 - acc: 0.5353 - val_loss: 8.0059 - val_acc: 0.4347
Epoch 14/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.2584 - acc: 0.5407Epoch 00014: val_loss improved from 8.00593 to 7.89369, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 7.2415 - acc: 0.5418 - val_loss: 7.8937 - val_acc: 0.4467
Epoch 15/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.2199 - acc: 0.5462Epoch 00015: val_loss improved from 7.89369 to 7.87753, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 7.2224 - acc: 0.5461 - val_loss: 7.8775 - val_acc: 0.4503
Epoch 16/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.2077 - acc: 0.5494Epoch 00016: val_loss improved from 7.87753 to 7.85807, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 7.2127 - acc: 0.5491 - val_loss: 7.8581 - val_acc: 0.4479
Epoch 17/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.1901 - acc: 0.5514Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 254us/step - loss: 7.2067 - acc: 0.5503 - val_loss: 7.8854 - val_acc: 0.4479
Epoch 18/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.1414 - acc: 0.5509Epoch 00018: val_loss improved from 7.85807 to 7.80382, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 7.1445 - acc: 0.5507 - val_loss: 7.8038 - val_acc: 0.4539
Epoch 19/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.0005 - acc: 0.5557Epoch 00019: val_loss improved from 7.80382 to 7.69904, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 7.0202 - acc: 0.5545 - val_loss: 7.6990 - val_acc: 0.4575
Epoch 20/20
6480/6680 [============================>.] - ETA: 0s - loss: 6.9067 - acc: 0.5593Epoch 00020: val_loss improved from 7.69904 to 7.58189, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 6.8820 - acc: 0.5608 - val_loss: 7.5819 - val_acc: 0.4527
Test accuracy: 45.5742%
In [94]:
#Preliminary Test on Inception
### Obtain bottleneck features from Inception.
bottleneck_features = np.load('bottleneck_features/DogInceptionV3Data.npz')
train_Inception = bottleneck_features['train']
valid_Inception = bottleneck_features['valid']
test_Inception = bottleneck_features['test']
### Define your architecture.
Inception_model = Sequential()
Inception_model.add(GlobalAveragePooling2D(input_shape=train_Inception.shape[1:]))
Inception_model.add(Dense(133, activation='softmax'))
Inception_model.summary()
### Compile the model.
Inception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
### Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Inception.hdf5', 
                               verbose=1, save_best_only=True)
Inception_model.fit(train_Inception, train_targets, 
          validation_data=(valid_Inception, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
### Load the model weights with the best validation loss.
Inception_model.load_weights('saved_models/weights.best.Inception.hdf5')
### Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
Inception_predictions = [np.argmax(Inception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Inception]
# report test accuracy
test_accuracy = 100*np.sum(np.array(Inception_predictions)==np.argmax(test_targets, axis=1))/len(Inception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_17  (None, 2048)              0         
_________________________________________________________________
dense_34 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6520/6680 [============================>.] - ETA: 0s - loss: 1.1629 - acc: 0.7044Epoch 00001: val_loss improved from inf to 0.71350, saving model to saved_models/weights.best.Inception.hdf5
6680/6680 [==============================] - 3s 408us/step - loss: 1.1500 - acc: 0.7066 - val_loss: 0.7135 - val_acc: 0.8120
Epoch 2/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.4733 - acc: 0.8559Epoch 00002: val_loss improved from 0.71350 to 0.69324, saving model to saved_models/weights.best.Inception.hdf5
6680/6680 [==============================] - 2s 310us/step - loss: 0.4730 - acc: 0.8564 - val_loss: 0.6932 - val_acc: 0.8299
Epoch 3/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.3643 - acc: 0.8891Epoch 00003: val_loss improved from 0.69324 to 0.67006, saving model to saved_models/weights.best.Inception.hdf5
6680/6680 [==============================] - 2s 313us/step - loss: 0.3634 - acc: 0.8895 - val_loss: 0.6701 - val_acc: 0.8371
Epoch 4/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.2938 - acc: 0.9097Epoch 00004: val_loss improved from 0.67006 to 0.65323, saving model to saved_models/weights.best.Inception.hdf5
6680/6680 [==============================] - 2s 316us/step - loss: 0.2913 - acc: 0.9102 - val_loss: 0.6532 - val_acc: 0.8383
Epoch 5/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.2279 - acc: 0.9285Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 0.2322 - acc: 0.9280 - val_loss: 0.6911 - val_acc: 0.8407
Epoch 6/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.2000 - acc: 0.9352Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s 315us/step - loss: 0.2000 - acc: 0.9352 - val_loss: 0.7597 - val_acc: 0.8383
Epoch 7/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1695 - acc: 0.9488Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 0.1695 - acc: 0.9487 - val_loss: 0.7596 - val_acc: 0.8491
Epoch 8/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.1431 - acc: 0.9546Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 0.1434 - acc: 0.9543 - val_loss: 0.7685 - val_acc: 0.8419
Epoch 9/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.1183 - acc: 0.9633Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.1179 - acc: 0.9630 - val_loss: 0.8319 - val_acc: 0.8503
Epoch 10/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.1086 - acc: 0.9656Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.1083 - acc: 0.9657 - val_loss: 0.7510 - val_acc: 0.8467
Epoch 11/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0895 - acc: 0.9710Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 0.0899 - acc: 0.9708 - val_loss: 0.8089 - val_acc: 0.8611
Epoch 12/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0834 - acc: 0.9739Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 0.0827 - acc: 0.9741 - val_loss: 0.8649 - val_acc: 0.8479
Epoch 13/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0717 - acc: 0.9785Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 0.0707 - acc: 0.9787 - val_loss: 0.8612 - val_acc: 0.8491
Epoch 14/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0605 - acc: 0.9817Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.0613 - acc: 0.9814 - val_loss: 0.8715 - val_acc: 0.8455
Epoch 15/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0576 - acc: 0.9817Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 0.0574 - acc: 0.9817 - val_loss: 0.8474 - val_acc: 0.8575
Epoch 16/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.0492 - acc: 0.9842Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 0.0485 - acc: 0.9844 - val_loss: 0.8564 - val_acc: 0.8647
Epoch 17/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0434 - acc: 0.9867Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 0.0432 - acc: 0.9867 - val_loss: 0.8752 - val_acc: 0.8491
Epoch 18/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0391 - acc: 0.9883Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 0.0390 - acc: 0.9883 - val_loss: 0.9303 - val_acc: 0.8515
Epoch 19/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0357 - acc: 0.9888Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 0.0360 - acc: 0.9888 - val_loss: 0.9358 - val_acc: 0.8419
Epoch 20/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0307 - acc: 0.9910Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 0.0302 - acc: 0.9912 - val_loss: 0.8883 - val_acc: 0.8659
Test accuracy: 79.4258%
In [93]:
#Preliminary Test on ResNet50
### Obtain bottleneck features from Inception.
bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']
### Define your architecture.
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dense(133, activation='softmax'))
Resnet50_model.summary()
### Compile the model.
Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
### Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1, save_best_only=True)
Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
### Load the model weights with the best validation loss.
Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')
### Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]
# report test accuracy
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_16  (None, 2048)              0         
_________________________________________________________________
dense_33 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6480/6680 [============================>.] - ETA: 0s - loss: 1.6616 - acc: 0.5892Epoch 00001: val_loss improved from inf to 0.86829, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 328us/step - loss: 1.6362 - acc: 0.5946 - val_loss: 0.8683 - val_acc: 0.7473
Epoch 2/20
6440/6680 [===========================>..] - ETA: 0s - loss: 0.4369 - acc: 0.8637Epoch 00002: val_loss improved from 0.86829 to 0.69999, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 234us/step - loss: 0.4357 - acc: 0.8636 - val_loss: 0.7000 - val_acc: 0.7868
Epoch 3/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.2579 - acc: 0.9197Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 2s 232us/step - loss: 0.2623 - acc: 0.9187 - val_loss: 0.7243 - val_acc: 0.7856
Epoch 4/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.1757 - acc: 0.9440Epoch 00004: val_loss improved from 0.69999 to 0.65918, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 233us/step - loss: 0.1756 - acc: 0.9439 - val_loss: 0.6592 - val_acc: 0.8120
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.1210 - acc: 0.9617Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 234us/step - loss: 0.1208 - acc: 0.9618 - val_loss: 0.7556 - val_acc: 0.8048
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0910 - acc: 0.9734Epoch 00006: val_loss improved from 0.65918 to 0.64209, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 236us/step - loss: 0.0908 - acc: 0.9735 - val_loss: 0.6421 - val_acc: 0.8311
Epoch 7/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0643 - acc: 0.9790Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 231us/step - loss: 0.0648 - acc: 0.9787 - val_loss: 0.6992 - val_acc: 0.8120
Epoch 8/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0479 - acc: 0.9848Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 271us/step - loss: 0.0480 - acc: 0.9849 - val_loss: 0.6831 - val_acc: 0.8311
Epoch 9/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0379 - acc: 0.9884Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 232us/step - loss: 0.0381 - acc: 0.9883 - val_loss: 0.6979 - val_acc: 0.8275
Epoch 10/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.0265 - acc: 0.9929Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 233us/step - loss: 0.0266 - acc: 0.9928 - val_loss: 0.7157 - val_acc: 0.8228
Epoch 11/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0217 - acc: 0.9943Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 232us/step - loss: 0.0214 - acc: 0.9945 - val_loss: 0.7546 - val_acc: 0.8323
Epoch 12/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0169 - acc: 0.9960Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 230us/step - loss: 0.0172 - acc: 0.9958 - val_loss: 0.7794 - val_acc: 0.8347
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0151 - acc: 0.9964Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 233us/step - loss: 0.0151 - acc: 0.9964 - val_loss: 0.8234 - val_acc: 0.8263
Epoch 14/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0121 - acc: 0.9968Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 230us/step - loss: 0.0129 - acc: 0.9967 - val_loss: 0.8488 - val_acc: 0.8240
Epoch 15/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0100 - acc: 0.9975Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 233us/step - loss: 0.0105 - acc: 0.9975 - val_loss: 0.8371 - val_acc: 0.8299
Epoch 16/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.0070 - acc: 0.9981Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 231us/step - loss: 0.0082 - acc: 0.9979 - val_loss: 0.8869 - val_acc: 0.8251
Epoch 17/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.9983Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 232us/step - loss: 0.0080 - acc: 0.9981 - val_loss: 0.8421 - val_acc: 0.8204
Epoch 18/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0066 - acc: 0.9985Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 232us/step - loss: 0.0066 - acc: 0.9984 - val_loss: 0.8960 - val_acc: 0.8299
Epoch 19/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.0056 - acc: 0.9981Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 232us/step - loss: 0.0059 - acc: 0.9981 - val_loss: 0.9237 - val_acc: 0.8263
Epoch 20/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.9988Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 231us/step - loss: 0.0059 - acc: 0.9987 - val_loss: 0.9562 - val_acc: 0.8240
Test accuracy: 81.6986%

Preliminary Accuracy for models:

  • VGG19: 45.5742%
  • Inception: 79.4258%
  • ResNet50: 81.6986%
  • Xception: Nil (not enough storage to load data)

Use ResNet50 model for improvement and further implementation.

In [7]:
bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_ResNet = bottleneck_features['train']
In [8]:
train_ResNet.shape
Out[8]:
(6680, 1, 1, 2048)
In [10]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_ResNet = bottleneck_features['train']
valid_ResNet = bottleneck_features['valid']
test_ResNet = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

Construct a convnet that consist of following:

  • Uses the the pre-trained model as a fixed feature extractor
  • Add fully connected layer with 256 neurons, using 'relu' activation function
  • Add a dropout for regularization
  • Add fully connected layer with 133 neurons with a softmax function.
In [15]:
### TODO: Define your architecture.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.layers import BatchNormalization
from keras.callbacks import ModelCheckpoint  

ResNet_model = Sequential()
ResNet_model.add(GlobalAveragePooling2D(input_shape=train_ResNet.shape[1:]))
ResNet_model.add(Dense(256, activation='relu'))
ResNet_model.add(Dropout(0.4))
ResNet_model.add(Dense(133, activation='softmax'))
ResNet_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 2048)              0         
_________________________________________________________________
dense_3 (Dense)              (None, 256)               524544    
_________________________________________________________________
dropout_2 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               34181     
=================================================================
Total params: 558,725
Trainable params: 558,725
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [16]:
### TODO: Compile the model.
ResNet_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [17]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.ResNet50.hdf5', 
                               verbose=1, save_best_only=True)

history = ResNet_model.fit(train_ResNet, train_targets, 
          validation_data=(valid_ResNet, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6580/6680 [============================>.] - ETA: 0s - loss: 2.7348 - acc: 0.3638Epoch 00001: val_loss improved from inf to 0.99291, saving model to saved_models/weights.best.ResNet50.hdf5
6680/6680 [==============================] - 2s 362us/step - loss: 2.7168 - acc: 0.3666 - val_loss: 0.9929 - val_acc: 0.7437
Epoch 2/20
6540/6680 [============================>.] - ETA: 0s - loss: 1.1621 - acc: 0.6595Epoch 00002: val_loss improved from 0.99291 to 0.72193, saving model to saved_models/weights.best.ResNet50.hdf5
6680/6680 [==============================] - 2s 289us/step - loss: 1.1530 - acc: 0.6618 - val_loss: 0.7219 - val_acc: 0.7665
Epoch 3/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.8294 - acc: 0.7401Epoch 00003: val_loss improved from 0.72193 to 0.68439, saving model to saved_models/weights.best.ResNet50.hdf5
6680/6680 [==============================] - 2s 289us/step - loss: 0.8302 - acc: 0.7395 - val_loss: 0.6844 - val_acc: 0.7904
Epoch 4/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.6419 - acc: 0.7951Epoch 00004: val_loss improved from 0.68439 to 0.65069, saving model to saved_models/weights.best.ResNet50.hdf5
6680/6680 [==============================] - 2s 289us/step - loss: 0.6431 - acc: 0.7943 - val_loss: 0.6507 - val_acc: 0.7904
Epoch 5/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.5426 - acc: 0.8244Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 286us/step - loss: 0.5428 - acc: 0.8244 - val_loss: 0.6762 - val_acc: 0.8096
Epoch 6/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.4853 - acc: 0.8413Epoch 00006: val_loss improved from 0.65069 to 0.64488, saving model to saved_models/weights.best.ResNet50.hdf5
6680/6680 [==============================] - 2s 287us/step - loss: 0.4842 - acc: 0.8419 - val_loss: 0.6449 - val_acc: 0.8024
Epoch 7/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.4071 - acc: 0.8698Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 285us/step - loss: 0.4067 - acc: 0.8699 - val_loss: 0.6449 - val_acc: 0.8275
Epoch 8/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.3865 - acc: 0.8734Epoch 00008: val_loss improved from 0.64488 to 0.63920, saving model to saved_models/weights.best.ResNet50.hdf5
6680/6680 [==============================] - 2s 281us/step - loss: 0.3851 - acc: 0.8735 - val_loss: 0.6392 - val_acc: 0.8263
Epoch 9/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.3524 - acc: 0.8863Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 280us/step - loss: 0.3510 - acc: 0.8865 - val_loss: 0.7293 - val_acc: 0.8180
Epoch 10/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.3097 - acc: 0.8967Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 279us/step - loss: 0.3102 - acc: 0.8969 - val_loss: 0.6863 - val_acc: 0.8251
Epoch 11/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.2904 - acc: 0.9036Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 278us/step - loss: 0.2900 - acc: 0.9039 - val_loss: 0.7129 - val_acc: 0.8204
Epoch 12/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.2749 - acc: 0.9074Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 280us/step - loss: 0.2735 - acc: 0.9078 - val_loss: 0.7120 - val_acc: 0.8192
Epoch 13/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.2374 - acc: 0.9223Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 281us/step - loss: 0.2362 - acc: 0.9225 - val_loss: 0.7452 - val_acc: 0.8156
Epoch 14/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.2491 - acc: 0.9231Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 281us/step - loss: 0.2496 - acc: 0.9232 - val_loss: 0.7242 - val_acc: 0.8120
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.2304 - acc: 0.9263Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 279us/step - loss: 0.2299 - acc: 0.9265 - val_loss: 0.8416 - val_acc: 0.8096
Epoch 16/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.2216 - acc: 0.9323Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 280us/step - loss: 0.2209 - acc: 0.9325 - val_loss: 0.8558 - val_acc: 0.8072
Epoch 17/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.2169 - acc: 0.9314Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 286us/step - loss: 0.2139 - acc: 0.9322 - val_loss: 0.7782 - val_acc: 0.8275
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.2180 - acc: 0.9313Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 281us/step - loss: 0.2182 - acc: 0.9314 - val_loss: 0.8923 - val_acc: 0.8251
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.1805 - acc: 0.9396Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 280us/step - loss: 0.1796 - acc: 0.9398 - val_loss: 0.8455 - val_acc: 0.8467
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.1997 - acc: 0.9366Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 280us/step - loss: 0.1988 - acc: 0.9367 - val_loss: 0.8946 - val_acc: 0.8359
In [18]:
import matplotlib.pyplot as plt
def plot_acc_loss(history):
    fig = plt.figure(figsize=(10,5))
    plt.subplot(1, 2, 1)
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'validation'], loc='upper left')
 
    plt.subplot(1, 2, 2)
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper right')
    plt.show()
 
plot_acc_loss(history)

The current model is overfitted. Reduce the complexity of the dense layer and dropout rate to improve the model.

In [19]:
### Re-define your architecture.
ResNet_model = Sequential()
ResNet_model.add(GlobalAveragePooling2D(input_shape=train_ResNet.shape[1:]))
ResNet_model.add(Dense(128, activation='relu'))
ResNet_model.add(Dropout(0.5))
ResNet_model.add(Dense(133, activation='softmax'))
ResNet_model.summary()

#Compile the model.
ResNet_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

#Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.ResNet50_final.hdf5', 
                               verbose=1, save_best_only=True)

history = ResNet_model.fit(train_ResNet, train_targets, 
          validation_data=(valid_ResNet, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
plot_acc_loss(history)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 2048)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 128)               262272    
_________________________________________________________________
dropout_3 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 133)               17157     
=================================================================
Total params: 279,429
Trainable params: 279,429
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6560/6680 [============================>.] - ETA: 0s - loss: 3.5929 - acc: 0.1976Epoch 00001: val_loss improved from inf to 1.62627, saving model to saved_models/weights.best.ResNet50_final.hdf5
6680/6680 [==============================] - 2s 320us/step - loss: 3.5755 - acc: 0.1996 - val_loss: 1.6263 - val_acc: 0.6228
Epoch 2/20
6640/6680 [============================>.] - ETA: 0s - loss: 1.8482 - acc: 0.4992Epoch 00002: val_loss improved from 1.62627 to 0.95451, saving model to saved_models/weights.best.ResNet50_final.hdf5
6680/6680 [==============================] - 2s 274us/step - loss: 1.8458 - acc: 0.5000 - val_loss: 0.9545 - val_acc: 0.7305
Epoch 3/20
6560/6680 [============================>.] - ETA: 0s - loss: 1.3440 - acc: 0.6117Epoch 00003: val_loss improved from 0.95451 to 0.78309, saving model to saved_models/weights.best.ResNet50_final.hdf5
6680/6680 [==============================] - 2s 268us/step - loss: 1.3417 - acc: 0.6124 - val_loss: 0.7831 - val_acc: 0.7497
Epoch 4/20
6520/6680 [============================>.] - ETA: 0s - loss: 1.0955 - acc: 0.6706Epoch 00004: val_loss improved from 0.78309 to 0.71396, saving model to saved_models/weights.best.ResNet50_final.hdf5
6680/6680 [==============================] - 2s 269us/step - loss: 1.0884 - acc: 0.6713 - val_loss: 0.7140 - val_acc: 0.7796
Epoch 5/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.9741 - acc: 0.7008Epoch 00005: val_loss improved from 0.71396 to 0.67787, saving model to saved_models/weights.best.ResNet50_final.hdf5
6680/6680 [==============================] - 2s 268us/step - loss: 0.9691 - acc: 0.7022 - val_loss: 0.6779 - val_acc: 0.7796
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.8967 - acc: 0.7254Epoch 00006: val_loss improved from 0.67787 to 0.64824, saving model to saved_models/weights.best.ResNet50_final.hdf5
6680/6680 [==============================] - 2s 266us/step - loss: 0.8953 - acc: 0.7256 - val_loss: 0.6482 - val_acc: 0.7868
Epoch 7/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.8180 - acc: 0.7520Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 261us/step - loss: 0.8206 - acc: 0.7510 - val_loss: 0.7054 - val_acc: 0.8048
Epoch 8/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.7370 - acc: 0.7706Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 265us/step - loss: 0.7364 - acc: 0.7711 - val_loss: 0.6986 - val_acc: 0.7892
Epoch 9/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.7400 - acc: 0.7748Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 265us/step - loss: 0.7367 - acc: 0.7754 - val_loss: 0.6721 - val_acc: 0.7988
Epoch 10/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.6551 - acc: 0.7945Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 265us/step - loss: 0.6570 - acc: 0.7942 - val_loss: 0.6753 - val_acc: 0.8012
Epoch 11/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.6346 - acc: 0.8017Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 264us/step - loss: 0.6341 - acc: 0.8021 - val_loss: 0.7198 - val_acc: 0.8048
Epoch 12/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.6062 - acc: 0.8140Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 264us/step - loss: 0.6046 - acc: 0.8144 - val_loss: 0.6736 - val_acc: 0.8048
Epoch 13/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.5807 - acc: 0.8115Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 264us/step - loss: 0.5822 - acc: 0.8114 - val_loss: 0.7236 - val_acc: 0.8036
Epoch 14/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.5737 - acc: 0.8249Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 272us/step - loss: 0.5724 - acc: 0.8250 - val_loss: 0.6747 - val_acc: 0.8060
Epoch 15/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.5541 - acc: 0.8191Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 265us/step - loss: 0.5583 - acc: 0.8186 - val_loss: 0.6947 - val_acc: 0.8036
Epoch 16/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.5112 - acc: 0.8392Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 266us/step - loss: 0.5119 - acc: 0.8386 - val_loss: 0.7638 - val_acc: 0.8060
Epoch 17/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.4975 - acc: 0.8397Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 265us/step - loss: 0.4976 - acc: 0.8395 - val_loss: 0.7508 - val_acc: 0.8024
Epoch 18/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.4824 - acc: 0.8479Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 265us/step - loss: 0.4818 - acc: 0.8479 - val_loss: 0.7231 - val_acc: 0.8156
Epoch 19/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.4426 - acc: 0.8551Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 266us/step - loss: 0.4429 - acc: 0.8552 - val_loss: 0.7388 - val_acc: 0.8096
Epoch 20/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.4650 - acc: 0.8557Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 266us/step - loss: 0.4673 - acc: 0.8551 - val_loss: 0.8487 - val_acc: 0.8036

The overfitting issue in the model has improved with reduction neuron in dense layer to 128 and increasing dropout to 0.5.

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [20]:
### TODO: Load the model weights with the best validation loss.
ResNet_model.load_weights('saved_models/weights.best.ResNet50_final.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [21]:
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
ResNet_predictions = [np.argmax(ResNet_model.predict(np.expand_dims(feature, axis=0))) for feature in test_ResNet]

# report test accuracy
test_accuracy = 100*np.sum(np.array(ResNet_predictions)==np.argmax(test_targets, axis=1))/len(ResNet_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 78.3493%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
import pandas as pd
import cv2              
from glob import glob
import matplotlib.pyplot as plt                        
%matplotlib inline       
from keras.preprocessing import image                  
from tqdm import tqdm
from extract_bottleneck_features import *
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.applications.resnet50 import ResNet50
from keras.applications.resnet50 import preprocess_input, decode_predictions
Using TensorFlow backend.
In [2]:
# load list of dog names
dog_names = pd.read_csv('dog_names.csv')
dog_names = list(dog_names['breed'])
In [40]:
#Load Dog Detector
# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
def ResNet50_predict_labels(img_path):
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 
#Load Face Detector
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0
In [16]:
### Define your architecture.
ResNet_model = Sequential()
ResNet_model.add(GlobalAveragePooling2D(input_shape=(1, 1, 2048)))
ResNet_model.add(Dense(128, activation='relu'))
ResNet_model.add(Dropout(0.5))
ResNet_model.add(Dense(133, activation='softmax'))
#ResNet_model.summary()

#Compile the model.
ResNet_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
In [17]:
def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)
In [18]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.


#Load the model weights with the best validation loss.
ResNet_model.load_weights('saved_models/weights.best.ResNet50_final.hdf5')

def Resnet50_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = ResNet_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    argmax_index = np.argmax(predicted_vector)
    confidence = predicted_vector[0][argmax_index]
    confidence = round(float(confidence),2)
    dog = dog_names[argmax_index]
    dog_class = dog.split('.')[0][-3::]
    dog_breed = dog.split('.')[1]
    dog_breed = dog_breed.replace('_',' ')
    return confidence,dog_class,dog_breed
In [19]:
#Test prediction with images
img_folder = 'images/'
path = img_folder+'*.jpg'
samples = glob(path)
for img_path in samples[0:3]:   
    confidence, dog_class, dog_breed = Resnet50_predict_breed(img_path)
    print('Prediction: Confidence-{:0.2f}, Class-{}, Breed-{}'.format(confidence,dog_class,dog_breed))
    img = plt.imread(img_path)
    plt.imshow(img)
    plt.show()
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
94658560/94653016 [==============================] - 2s 0us/step
Prediction: Confidence-0.75, Class-047, Breed-Chesapeake bay retriever
Prediction: Confidence-0.99, Class-037, Breed-Brittany
Prediction: Confidence-0.98, Class-055, Breed-Curly-coated retriever

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

A sample image and output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

This photo looks like an Afghan Hound.

(IMPLEMENTATION) Write your Algorithm

In [26]:
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
def identify_face(img):
    # convert image to grayscale
    grayscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # detect faces
    faces = face_cascade.detectMultiScale(grayscale_img, scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE)

    face_box, face_coords = None, []

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3)
        cv2.putText(img,'Human Face',(x-50,y-20),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),3)
        face_box = img[y:y+h, x:x+w]
        face_coords = [x,y,w,h]

    return img, face_box, face_coords
In [46]:
def predict_picture(img_path):
    img = plt.imread(img_path)
    if dog_detector(img_path):
        confidence, dog_class, dog_breed = Resnet50_predict_breed(img_path)
        input_text = dog_breed +'('+str(confidence)+')'
        cv2.putText(img, input_text, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0),3)
        print('This photo looks like a dog of breed {}.'.format(dog_breed))    
    elif face_detector(img_path):
        a, face_box, coords = identify_face(img)
        confidence, dog_class, dog_breed = Resnet50_predict_breed(img_path)
        input_text = dog_breed +'('+str(confidence)+')'
        cv2.putText(img, input_text, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0),3)
        print('This photo looks like a human and resembles a {}.'.format(dog_breed))
    else:
        print('Opps this photo looks like neither human nor dog.') 
    
    plt.imshow(img)
    plt.show()

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

  • The algorithm is performing better than expected. Out of the 8 tested dog images, 6 were predicted correctly with confidence rate of more than 70%.
  • One of the dog image is Shih Tzu (not in the trained classes) and is misintepreted as a Maltese. Also a chihuahua is misclassified as a German pinscher.
  • For the case of misclassification of shih tzu, it would improve the algorithm with more training data of more dog breeds.
  • For the case of misclassification of pinscher could be due to dogs which looks similarbut of different size. Would improve the algorithm if there is a way to intepret dog size from the image.
  • The algorithm can be improved by differentiate predicted dog breed of low confidence rate that is probably misclassified by setting a threshold to the confidence rate of prediction.
In [47]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
img_folder = 'images_test/'
path = img_folder+'*.jpg'
samples = glob(path)
for img_path in samples:
    predict_picture(img_path)
Opps this photo looks like neither human nor dog.
Opps this photo looks like neither human nor dog.
This photo looks like a dog of breed Maltese.
This photo looks like a dog of breed Brussels griffon.
This photo looks like a human and resembles a Norwich terrier.
This photo looks like a dog of breed Chow chow.
This photo looks like a dog of breed German pinscher.
This photo looks like a dog of breed German shepherd dog.
This photo looks like a dog of breed Pekingese.
This photo looks like a dog of breed Bulldog.
This photo looks like a human and resembles a Great dane.
This photo looks like a dog of breed Italian greyhound.

Improvement to algorithm as follows:

In [51]:
def predict_pictureV2(img_path,threshold):
    img = plt.imread(img_path)
    if dog_detector(img_path):
        confidence, dog_class, dog_breed = Resnet50_predict_breed(img_path)
        if confidence >= threshold:
            input_text = dog_breed +'('+str(confidence)+')'
            cv2.putText(img, input_text, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0),3)
            print('This photo looks like a dog of breed {}.'.format(dog_breed))    
        else:
            print('This photo looks a dog but we do not know the breed.')    
    elif face_detector(img_path):
        a, face_box, coords = identify_face(img)
        confidence, dog_class, dog_breed = Resnet50_predict_breed(img_path)
        input_text = dog_breed +'('+str(confidence)+')'
        cv2.putText(img, input_text, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0),3)
        print('This photo looks like a human and resembles a {}.'.format(dog_breed))
    else:
        print('Opps this photo looks like neither human nor dog.') 
        
    plt.imshow(img)
    plt.show()
In [52]:
#Test on improved algorithm
img_folder = 'images_test/'
path = img_folder+'*.jpg'
samples = glob(path)
threshold = 0.7
for img_path in samples:
    predict_pictureV2(img_path, threshold)
Opps this photo looks like neither human nor dog.
Opps this photo looks like neither human nor dog.
This photo looks a dog but we do not know the breed.
This photo looks like a dog of breed Brussels griffon.
This photo looks like a human and resembles a Norwich terrier.
This photo looks like a dog of breed Chow chow.
This photo looks a dog but we do not know the breed.
This photo looks like a dog of breed German shepherd dog.
This photo looks like a dog of breed Pekingese.
This photo looks like a dog of breed Bulldog.
This photo looks like a human and resembles a Great dane.
This photo looks like a dog of breed Italian greyhound.